var ble_master = require('../ble/ble_master.js');
const order = ['demo1', 'demo2', 'demo3']

let curve = {
  mW: 345, //canvas宽
  mH: 250, //canvas高
  mCenter: 180, //中心点
  hCenter: 125, //中心点
  points: []
};
// pages/body_temp/main_page.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 数字提示
    numShiow: false,
    tipLeft: 0, //提示的x坐标
    tipHeight: 0, //提示线条的高度
    curveColText: ['100', '80', '60', '40', '20', '0', '0', '5', '9', '30'], //y轴
    // 主要数据
    curve: {
      bgColor: "#fcede0",
      date: ["10-20", "10-21", "10-22", "10-23", "10-24", "10-25", "10-26", "10-27", "10-28", "10-29", "10-30", "10-31" ],
      lineColor: "#567895",
      list: [32, 50, 76, 70, 10, 85, 85, 88, 57, 21, 30, 58],
      name: "color",
      xData: [],
    },
    tipIndex: 0,
    whatShow: false,
    getshow: false,
  

    dev_basic_info: {
      bleHeadName: "TBP OAD",
      bleServiceUUID: "F000FFF0-0451-4000-B000-000000000000",
      bleCharUUID: "F000FFF1-0451-4000-B000-000000000000",
    },

    user_storage_data: {
      data_key: 'btemp',
      user_data: []
    },
  

    canvas_info: {
      canvas_width: 300,
      canvas_height: 300,
      canvas_step_witdh: 30,
      row_text_x_shift: 29.5,
      row_text_y_shift: 220,
      line_x_shift: 29.5,
      line_y_shift: 200,
      line_y_times: 1.5,
    },
    last_point_position: {
      x: 0,
      y: 200,
      index: 0,
    },
    last_data: "??",

    cmd_list: {
      start_adc_cmd: "start"
    },
    // toView: 'green'

    ntc_data: {
      b: 0,
      r: 0,
      T: 0,
    },

  },


  get_canvas_basic_info: function() {
    var tp = this.data.canvas_info
    tp.x = this.data.canvas_info.line_x_shift
    tp.y = this.data.canvas_info.line_y_shift - 0 * this.data.canvas_info.line_y_times
    this.setData({
      canvas_info: tp
    })

    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        let canvas_info = that.data.canvas_info
        canvas_info.canvas_width = res.windowWidth - 2 + 100
        // canvas_info.canvas_step_witdh = canvas_info.canvas_width / 10
        that.setData({
          canvas_info: canvas_info
        });
      },
    })

    // // Get storage data
    // try {
    //   let user_data_t = this.data.user_storage_data
    //   user_data_t.user_data = wx.getStorageSync(this.data.user_storage_data.data_key)
    //   if (user_data_t.user_data) {
    //     // Do something with return value
    //     console.log('data get')
    //     console.log(user_data_t.user_data.length)
    //     this.setData({
    //       user_storage_data: user_data_t
    //     })
    //   }
    // } catch (e) {
    //   // Do something when catch error
    //   console.log(e)
    // }
  },

  main_clear_history: function() {
    let empty_data = this.data.user_storage_data
    empty_data.user_data = []
    this.setData({
      user_storage_data: empty_data
    })
    try {
      wx.setStorageSync(this.data.user_storage_data.data_key, this.data.user_storage_data.user_data)
    } catch (e) { 
      console.log(e)
    }
  },

  canvas_ready: function() {
    let user_data_t = this.data.user_storage_data
    if(user_data_t.user_data.length == 0) {
      user_data_t.user_data = []
    }
    // for(let i = 0; i < 10; i++) {
    //   user_data_t.user_data.push({
    //     x: i,
    //     y: parseFloat((Math.random() * 100).toFixed(1))
    //   })
    // }
    // // console.log(user_data_t)
    // this.setData({
    //   user_storage_data: user_data_t
    // })
    // let empty_data = []
    // try {
    //   wx.setStorageSync(this.data.user_storage_data.data_key, this.data.user_storage_data.user_data)
    // } catch (e) { 
    //   console.log(e)
    // }

    // let t_curve = this.data.curve
    // // t_curve.list.forEach(d => {
    // //   d = parseFloat((Math.random() * 100).toFixed(1) )
    // // })
    // for(let i = 0; i < t_curve.list.length; i++) {
    //   t_curve.list[i] = parseFloat((Math.random() * 100).toFixed(1) )
    // }
    
    // this.setData({
    //   curve : t_curve
    // })

    // let {curveColText } = this.data //y坐标
    // let {bgColor,date,lineColor,list,xData } = this.data.curve //y坐标
    // let curveCanvas = wx.createCanvasContext('curveCanvas');
    // // this.drawLineRowText(curveText, curveCtx, xData); //绘制横坐标文字
    // // this.drawCurve(curveCanvas, curveColText, date, list, xData, lineColor, bgColor);

    this.context = wx.createCanvasContext('mainCanvas')
    // // mainCanvas.setFillStyle('lightgrey')
    // // mainCanvas.fillRect(1, 1, this.data.canvas_info.canvas_width, this.data.canvas_info.canvas_height)

    // mainCanvas.beginPath()
    // mainCanvas.moveTo(30, 100)
    // mainCanvas.lineTo(60, 150)
    // mainCanvas.lineTo(90, 70)
    // mainCanvas.stroke()
    // mainCanvas.draw()

    // mainCanvas.save()

    // mainCanvas.beginPath()
    // mainCanvas.moveTo(90, 70)
    // mainCanvas.lineTo(120, 50)
    // mainCanvas.lineTo(150, 60)
    // // mainCanvas.lineTo(6 * this.data.canvas_info.canvas_step_witdh, this.data.canvas_info.canvas_height - 15)
    // // mainCanvas.lineTo(7 * this.data.canvas_info.canvas_step_witdh, this.data.canvas_info.canvas_height - 50)
    // // mainCanvas.lineTo(8 * this.data.canvas_info.canvas_step_witdh, this.data.canvas_info.canvas_height - 15)
    // // mainCanvas.lineTo(9 * this.data.canvas_info.canvas_step_witdh, this.data.canvas_info.canvas_height - 50)
    // // mainCanvas.lineTo(10 * this.data.canvas_info.canvas_step_witdh, this.data.canvas_info.canvas_height - 15)
    // // mainCanvas.lineTo(11 * this.data.canvas_info.canvas_step_witdh, this.data.canvas_info.canvas_height - 50)
    // // mainCanvas.lineTo(12 * this.data.canvas_info.canvas_step_witdh, this.data.canvas_info.canvas_height - 15)
    // // mainCanvas.lineTo(13 * this.data.canvas_info.canvas_step_witdh, this.data.canvas_info.canvas_height - 50)
    // mainCanvas.stroke()
    // mainCanvas.draw({
    //   reserve: true
    // })

    // mainCanvas.restore()

    console.log(this.data.user_storage_data.user_data.length)
    if(this.data.user_storage_data.user_data.length > 0) {
      // let canvas_info = this.data.canvas_info
      // canvas_info.canvas_width = (this.data.user_storage_data.user_data.length * this.data.canvas_info.canvas_step_witdh).toFixed()
      // console.log(canvas_info.canvas_width)
      // this.setData({
      //   canvas_info: canvas_info
      // })
      this.setGroupRowLineText(this.context, this.data.user_storage_data.user_data)
      this.addGroupDataPoint(this.context, this.data.user_storage_data.user_data)
    }
    
    this.context.draw()


    // this.initMainPageTimer()

    

    
  },

  drawWindowCanvas: function(datas) {
    let wdata = []
    let max_len = (this.data.canvas_info.canvas_width / this.data.canvas_info.canvas_step_witdh).toFixed() - 4
    // console.log(max_len)
    if(datas.length > max_len) {
      // console.log("Out of range")
      for(let i = datas.length - max_len; i < datas.length; i++) {
        wdata.push(datas[i])
      }
    } else {
      for(let i = 0; i < datas.length; i++) {
        wdata.push(datas[i])
      }
    }

    // console.log(wdata)

    this.setGroupRowLineText(this.context, wdata)
    this.addGroupDataPoint(this.context, wdata)
    this.context.draw(false)
  },
  addNewData: function(newdata) {
    // this.addNewDataRowText(this.context, newdata)
    // this.addNewDataPoint(this.context, newdata)
    this.setData({
      last_data: newdata
    })

    let user_data_t = this.data.user_storage_data
    user_data_t.user_data.push({
      x: this.data.last_point_position.index,
      y: newdata
    })

    // let canvas_info = this.data.canvas_info
    // canvas_info.canvas_width = (this.data.user_storage_data.user_data.length * this.data.canvas_info.canvas_step_witdh + this.data.canvas_info.row_text_x_shift).toFixed()
    // // console.log(canvas_info.canvas_width)
    // this.setData({
    //   canvas_info: canvas_info
    // })
    // console.log(user_data_t.user_data)

    this.setData({
      user_storage_data: user_data_t
    })
    try {
      wx.setStorageSync(this.data.user_storage_data.data_key, this.data.user_storage_data.user_data)
    } catch (e) { 
      console.log(e)
    }

    this.drawWindowCanvas(this.data.user_storage_data.user_data)
  },

  mainTimerCallback: function() {
    let newdata = parseFloat((Math.random() * 100).toFixed(1))
    this.addNewData(newdata)
  },

  initMainPageTimer: function() {
    this.data.mainPageTimer = setInterval(this.mainTimerCallback, 2000)
  },

  // 曲线
  drawCurve(curveCtx, curveColText, curveText, curveData, xData, LineColor, colorEnd) {
    // this.drawLineBg(curveCtx); //画横纵坐标框架
    // this.drawLineColText(curveColText, curveCtx); //绘制纵坐标文字
    // console.log(curveText)
    // console.log(xData)
    // console.log(curveData)
    // console.log(LineColor)
    // console.log(colorEnd)
    this.drawLineRowText(curveText, curveCtx, xData); //绘制横坐标文字
    this.drawCurveCtx(curveData, curveCtx, xData, LineColor, colorEnd); //绘制曲线
    curveCtx.draw();
  },

  setGroupRowLineText: function(canvas, data) {
    for(let i = 0; i < data.length; i++) {
      this.setRowLineText(canvas, data[i].y + "℃", this.data.canvas_info.canvas_step_witdh * i + this.data.canvas_info.row_text_x_shift, this.data.canvas_info.row_text_y_shift)
    }
  },
  setRowLineText: function(canvas, xdata, position_x, position_y) {
    // canvas.setFillStyle("#333")
    console.log(position_x)
    canvas.setFontSize(8)
    canvas.fillText(xdata, position_x, position_y)
  },
  addNewDataRowText(canvas, xdata) {
    let tp = this.data.last_point_position
    tp.index =  tp.index + 1
    canvas.setFontSize(8)
    canvas.fillText(xdata + "℃", this.data.canvas_info.canvas_step_witdh * tp.index + this.data.canvas_info.row_text_x_shift, this.data.canvas_info.row_text_y_shift)
  },

  addGroupDataPoint: function(canvas, data) {
    let tp = this.data.last_point_position
    tp.x = this.data.canvas_info.line_x_shift
    tp.y = this.data.canvas_info.line_y_shift - data[0].y * this.data.canvas_info.line_y_times

    for(let i = 1; i < data.length; i++) {
      canvas.moveTo(tp.x, tp.y)
      tp.x = this.data.canvas_info.line_x_shift + i * this.data.canvas_info.canvas_step_witdh
      tp.y = this.data.canvas_info.line_y_shift - data[i].y * this.data.canvas_info.line_y_times
      tp.index = i
      canvas.lineTo(tp.x, tp.y)
      canvas.stroke()
      this.setData({
        last_point_position: tp
      })
    }
  },
  addNewDataPoint: function(canvas, point_y) {
    // canvas.save()

    let tp = this.data.last_point_position
    canvas.moveTo(tp.x, tp.y)
    // tp.index = tp.index + 1
    tp.x = this.data.canvas_info.line_x_shift + tp.index * this.data.canvas_info.canvas_step_witdh
    tp.y = this.data.canvas_info.line_y_shift - point_y * this.data.canvas_info.line_y_times
    canvas.lineTo(tp.x, tp.y)
    this.setData({
      last_point_position: tp
    })
    canvas.stroke()
    // canvas.draw({
    //   reserve: true
    // })
    canvas.draw(true)
  },

  // 绘制横坐标文字
  drawLineRowText(mData, lineCtx, xData) {
    lineCtx.setFillStyle("#333");
    lineCtx.setFontSize(12); //设置字体
    for (let i = 0; i < mData.length; i++) {
      if (mData.length >= 3 && mData[1] != '') {
        lineCtx.fillText(mData[i], 20 + i * 49, 220);
        xData.push({
          tiem: mData[i],
          x: 20 + i * 49,
          y: 0
        })

        // lineCtx.fillText(mData[i][1], 15 + i * 65, 235);
      } else if (mData[1] == '') {
        // 数据小于等于2的时候的坐标
        lineCtx.fillText(mData[i], 60 + i * 90, 220);
        // lineCtx.fillText(mData[i][1], 35 + i * 80, 235);
        xData.push({
          tiem: mData[i],
          x: 20 + i * 49,
          y: 0
        })
      } else if (mData[2] == '') {
        // 数据小于等于1的时候的坐标
        lineCtx.fillText(mData[i], 20 + i * 90, 220);
        // lineCtx.fillText(mData[i][1], 35 + i * 80, 235);
        xData.push({
          tiem: mData[i],
          x: 20 + i * 49,
          y: 0
        })
      }
    }
    // this.setData({
    //   xData: xData
    // })
  },

  drawCurveCtx(mData, lineCtx, xData, LineColor, colorEnd) {
    curve.points = [];
    for (let i = 0; i < mData.length; i++) {
      curve.points.push({
        x: 29.5 + i * 52,
        y: 200 - mData[i] / 100 * 150
      });
    }
    // this.drawCurvePath(curve.points, lineCtx, LineColor, colorEnd);
    var point = getControlPoint(curve.points);
    this.drawCurveSign(point, lineCtx, LineColor)
    // 获取y轴做线条高度
    curve.points.forEach((v, i) => {
      xData[i].y = v.y
    })
  },

  // 绘制曲线背景
  drawCurvePath(path, ctx, LineColor, colorEnd) {
    var point = getControlPoint(path);
    ctx.beginPath();
    const grd = ctx.createLinearGradient(174, 180, 200, 0);
    grd.addColorStop(0, '#ffffff');
    grd.addColorStop(0.8, colorEnd);
    grd.addColorStop(1, colorEnd);
    ctx.setFillStyle(grd);
    ctx.setGlobalAlpha(0.8);
    ctx.beginPath();
    ctx.moveTo(29, 200);
    ctx.lineTo(curve.points[0].x, curve.points[0].y);
    var int = 0;
    for (let i = 0; i < curve.points.length; i++) {
      if (i == 0) {
        ctx.quadraticCurveTo(point[0].x, point[0].y, curve.points[1].x, curve.points[1].y);
        int = int + 1;
      } else if (i < curve.points.length - 2) {
        ctx.bezierCurveTo(point[int].x, point[int].y, point[int + 1].x, point[int + 1].y, curve.points[i + 1].x, curve.points[i + 1].y);
        int += 2;
      } else if (i == curve.points.length - 2) {
        ctx.quadraticCurveTo(point[point.length - 1].x, point[point.length - 1].y, curve.points[curve.points.length - 1].x, curve.points[curve.points.length - 1].y);
      }
    }
    ctx.lineTo(curve.points[curve.points.length - 1].x, 200);
    ctx.fill();
    ctx.closePath();
    // this.drawCurveSign(point, ctx, LineColor)
  },
// 绘制点加线
drawCurveSign(point, ctx, LineColor) {
  // 绘制线
  ctx.beginPath();
  ctx.setStrokeStyle(LineColor);
  ctx.setGlobalAlpha(1);
  ctx.setLineWidth(4);
  var int = 0;
  ctx.moveTo(curve.points[0].x - 20, curve.points[0].y);
  for (var i = 0; i < curve.points.length; i++) {
    if (i == 0) {
      ctx.quadraticCurveTo(point[0].x, point[0].y, curve.points[1].x, curve.points[1].y);
      int = int + 1;
    } else if (i < curve.points.length - 2) {
      ctx.bezierCurveTo(point[int].x, point[int].y, point[int + 1].x, point[int + 1].y, curve.points[i + 1].x, curve.points[i + 1].y);
      int += 2;
    } else if (i == curve.points.length - 2) {
      ctx.quadraticCurveTo(point[point.length - 1].x, point[point.length - 1].y, curve.points[curve.points.length - 1].x, curve.points[curve.points.length - 1].y);
    }
  }
  ctx.stroke();
  // 绘制点
  // ctx.beginPath();
  // ctx.setGlobalAlpha(1);
  // for (let i = 0; i < curve.points.length; i++) {
  //   ctx.beginPath();
  //   ctx.arc(curve.points[i].x, curve.points[i].y, 5, 0, 2 * Math.PI);
  //   console.log('点',curve.points[i].x, curve.points[i].y, 5, 0, 2 * Math.PI)
  //   ctx.setFillStyle("#3388FF");
  //   ctx.fill();
  //   ctx.closePath();
  // }
},
  




  scrollCanvas: function(e) {
    console.log(e);
    // let index = e.currentTarget.dataset.index
    // var canvasLen = e.detail.scrollLeft;
    //   this.setData({
    //     indexScroll: index,
    //     canvasLen: canvasLen
    //   })
  },
  

  init_ble_function: function() {
    ble_master.setLanguage2EN()
    this.ble_foundSpecialDev()
  },

  ble_foundSpecialDev: function() {
    ble_master.ble_onDeviceFound(this.christp_foundBluetoothDeviceCallback)
    ble_master.ble_openAdaptorandStartDiscovery()
  },

  christp_foundBluetoothDeviceCallback() {
    if (ble_master.ble_getDeviceinFoundDeviceListByName(this.data.dev_basic_info.bleHeadName)) {
      ble_master.ble_stopDiscovery(this.christp_afterStopBluetoothDiscovery)
    } 
  },

  christp_afterStopBluetoothDiscovery() {
    console.log("device found")
    ble_master.ble_connectToDevice(this.ble_connectSuccessCallback)
  },

  ble_connectSuccessCallback: function () {
    console.log("Connect to ble device " + ble_master.data.ble_device.deviceId + " success")
    wx.showToast({
      title: 'Connected',
    })
    if (false == ble_master.data.isNotifyOn) {
      ble_master.ble_turnOnNotify(this.data.dev_basic_info.bleServiceUUID, this.data.dev_basic_info.bleCharUUID, this.ble_turnOnNotifySuccessCallback)
    } else {
      console.log("the is notify on state is " + ble_master.data.isNotifyOn)
      this.ble_turnOnNotifySuccessCallback()
    }
  },

  ble_turnOnNotifySuccessCallback: function () {
    console.log("Trun on notify success in callback function")
    ble_master.ble_getNotifyData(this.ble_getNotifyDataCallback)
    
    let cmd_value = this.data.cmd_list.start_adc_cmd
    this.ble_sendData(ble_master.getCharsFromString(cmd_value))
  },

  ble_sendData: function (res) {
    if (ble_master.data.isConnected) {
      ble_master.ble_sendData(res)
    } else {
      console.log("ble device not connect")
    }
  },

  ble_getNotifyDataCallback: function (res) {
    let str = ble_master.getStringFromBuffer(res)
    // console.log(res)
    // console.log("Get notify data: " + str)

    var adc1 = ble_master.getIntFromString(str.substring(0, 4))
    var adc2 = ble_master.getIntFromString(str.substring(5, 9))

    // console.log(adc1, adc2)

    // adc2 = 
    var r2 = adc2 * 10 / (4096 - adc2)
    console.log(r2)

    this.addNewData(this.get_ntc_temp_by_register(r2))

    

    // let split_str = str.split(this.data.splitChar)
    // if (2 == split_str.length) {
    //   let cmd_head = split_str[0]
    //   // console.log("split_str[0] len is " + split_str[0].length)
    //   // console.log("split_str[1] len is " + split_str[1].length)
    //   let cmd_value = ble_master.getIntFromString(split_str[1])
    //   console.log(cmd_head + " " + cmd_value)
    //   this.ble_handleReceivedData(cmd_head, cmd_value)
    // } else {
    //   console.log("Get wrong data")
    // }
  },
  ntc_basic_data_ready: function() {
    var ntc_data = this.data.ntc_data

    var T45 = 45 + 273.15
    var T40 = 40 + 273.15
    var T30 = 30 + 273.15

    var R45 = 4.586894586894587
    var R40 = 5.419269798722756
    var R30 = 7.677844735667965
    // var R38 = 5.802470944688494

    var b1 = Math.log(R45 / R40) / ((1 / T45) - (1 / T40))
    var b2 = Math.log(R30 / R40) / ((1 / T30) - (1 / T40))
    var b3 = Math.log(R30 / R45) / ((1 / T30) - (1 / T45))

    ntc_data.b = (b1 + b2 + b3) / 3
    ntc_data.r = R40
    ntc_data.T = T40

    console.log(ntc_data)

    this.setData({
      ntc_data: ntc_data
    })

    // var cT = (1 / ((Math.log(R38 / R40) / tb) + (1 / T40))) - 273.15
    // console.log(cT)
  },

  get_ntc_temp_by_register: function(r) {
    var ntc_data = this.data.ntc_data
    var cT = (1 / ((Math.log(r / ntc_data.r) / ntc_data.b) + (1 / ntc_data.T))) - 273.15
    // console.log(cT)
    return cT.toFixed(1)
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.get_canvas_basic_info()
    this.ntc_basic_data_ready()
    this.init_ble_function()
    this.canvas_ready()

    // console.log(this.get_ntc_temp_by_register(11.3))
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
// quxian
// 折线变曲线
let Vector2 = function (x, y) {
  this.x = x;
  this.y = y;
};
Vector2.prototype = {
  "length": function () {
    return Math.sqrt(this.x * this.x + this.y * this.y);
  },
  "normalize": function () {
    let inv = 1 / this.length() == Infinity ? 0 : 1 / this.length();
    return new Vector2(this.x * inv, this.y * inv);
  },
  "add": function (v) {
    return new Vector2(this.x + v.x, this.y + v.y);
  },
  "multiply": function (f) {
    return new Vector2(this.x * f, this.y * f);
  },
  "dot": function (v) {
    return this.x * v.x + this.y * v.y;
  },
  "angle": function (v) {
    return Math.acos(this.dot(v) / (this.length() * v.length())) * 180 / Math.PI;
  }
};

function getControlPoint(path) {
  let rt = 0.3;
  let count = path.length - 2;
  let arr = [];
  for (let i = 0; i < count; i++) {
    let a = path[i];
    let b = path[i + 1];
    let c = path[i + 2];
    let v1 = new Vector2(a.x - b.x, a.y - b.y);
    let v2 = new Vector2(c.x - b.x, c.y - b.y);
    let v1Len = v1.length();
    let v2Len = v2.length();
    let centerV = v1.normalize().add(v2.normalize()).normalize();
    let ncp1 = new Vector2(centerV.y, centerV.x * -1);
    let ncp2 = new Vector2(centerV.y * -1, centerV.x);
    if (ncp1.angle(v1) < 90) {
      let p1 = ncp1.multiply(v1Len * rt).add(b);
      let p2 = ncp2.multiply(v2Len * rt).add(b);
      arr.push(p1, p2);
    } else {
      let p1 = ncp1.multiply(v2Len * rt).add(b);
      let p2 = ncp2.multiply(v1Len * rt).add(b);
      arr.push(p2, p1);
    }
  }
  return arr;
};